﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BabyNames
{
    class BabySortByDecade : IComparer<BabyName>
    {
        public BabySortByDecade(int decade)
        {
            this.decade = decade;
        }

        private int decade;

        public int Compare(BabyName x, BabyName y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    // If x is null and y is null, they're
                    // equal. 
                    return 0;
                }
                else
                {
                    // If x is null and y is not null, y
                    // is greater. 
                    return -1;
                }
            }
            else
            {
                // If x is not null...
                if (y == null)
                // ...and y is null, x is greater.
                {
                    return 1;
                }
                else
                {
                    // ...and y is not null, compare the 
                    // lengths of the two strings.
                    //
                    if (x.Rank(decade) == 0)
                        if (y.Rank(decade) == 0)
                            return 0;
                        else
                            return 1;
                    else
                        if (y.Rank(decade) == 0)
                            return -1;

                    var retval = x.Rank(decade).CompareTo(y.Rank(decade));

                    if (retval != 0)
                    {
                        // If the strings are not of equal length,
                        // the longer string is greater.
                        //
                        return retval;
                    }
                    else
                    {
                        // If the strings are of equal length,
                        // sort them with ordinary string comparison.
                        //
                        return x.CompareTo(y);
                    }
                }
            }
        }
    }
}
